package com.xsky.logic.role;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.basic.DateConverter;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.xsky.converter.XStreamClobConverter;
import com.xsky.database.dao.impl.BaseEntityDaoImpl;
import com.xsky.operation.vo.TabAccessMartrix;
import com.xsky.operation.vo.TabClient;
import com.xsky.operation.vo.TabEngineer;
import com.xsky.operation.vo.TabRole;
import com.xsky.operation.vo.TabRoleAccess;
import com.xsky.operation.vo.TabUserRole;

public class RoleLogic
{

	/*public String genPowerInfo() throws DocumentException, IOException
	{

		InputStream in = RoleLogic.class.getResourceAsStream("/config/power.xml");
		ByteArrayOutputStream bout = new ByteArrayOutputStream();

		byte[] buffer = new byte[1024];

		int num = in.read(buffer);

		while (num > 0)
		{
			bout.write(buffer, 0, num);
			num = in.read(buffer);
		}
		return new String(bout.toByteArray(), "utf-8");
	}*/
	public String genPowerInfo(String roleId) throws DocumentException, IOException
	{
		String result = "<data>";
		BaseEntityDaoImpl baseDao = new BaseEntityDaoImpl();
		List accessList = baseDao.findByHql("from TabRoleAccess model where model.roleId='"+roleId+"'");
		for(int i = 0; i < accessList.size(); i++)
		{
			TabRoleAccess entity = (TabRoleAccess)accessList.get(i);
			result+="<item>";
			result+="<accessCode>"+entity.getAccessCode()+"</accessCode>";
			result+="<accessId>"+entity.getAccessId()+"</accessId>";
			result+="<roleId>"+entity.getRoleId()+"</roleId>";
			result+="<id>"+entity.getId()+"</id>";
			result+="</item>";
		}
		result+="</data>";
		return result;
	}
	public String add(String xmlStr)//增加
	{
		BaseEntityDaoImpl baseDao = new BaseEntityDaoImpl();
		XStream xs = new XStream(new DomDriver());
		String defaultFormat = "yyyy-MM-dd";
		String[] acceptableFormat = {"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd","yyyy-MM"};
		xs.registerConverter(new DateConverter(defaultFormat,acceptableFormat));
		xs.registerConverter(new XStreamClobConverter());
		xs.alias("data", TabRole.class);
		TabRole entity = (TabRole)xs.fromXML(xmlStr);
		entity.setId(UUID.randomUUID().toString().substring(0,31));
		baseDao.insertEntity(entity);
		return "<data><result>ok</result><uuid>"+entity.getId()+"</uuid><info>添加成功</info></data>";
	}
	public String deleteById(String id)//删除
	{
		BaseEntityDaoImpl baseDao = new BaseEntityDaoImpl();
		baseDao.deleteByHql("delete TabRole model where model.id='"+id+"'");
		return "<data><result>ok</result><uuid></uuid><info>删除成功</info></data>";
	}
	public String delete(String xmlStr)//删除
	{
		String in = "(";
		try
		{
			Document document = DocumentHelper.parseText(xmlStr);
			List itemList = document.selectNodes("//root/item");
			Element element = null;
			for(int i = 0; i < itemList.size(); i++)
			{
				element = (Element)itemList.get(i);
				document = DocumentHelper.parseText(element.asXML());
				if(element.attribute("selected")==null)
				{
					
				}
				else
				{
					if("true".equals(element.attribute("selected").getData().toString()))
					{
						in+="'"+document.selectSingleNode("//item/id").getText()+"',";
					}
				}
			}
		} catch (DocumentException e)
		{
			e.printStackTrace();
		}
		in += ")";
		in = in.replace(",)", ")");
		BaseEntityDaoImpl baseDao = new BaseEntityDaoImpl();
		baseDao.deleteByHql("delete TabRole model where model.id in '"+in+"'");
		return "<data><result>ok</result><uuid></uuid><info>删除成功</info></data>";
	}
	public String deleteUserRoles(String xmlStr)//删除
	{
		String in = "(";
		try
		{
			Document document = DocumentHelper.parseText(xmlStr);
			List itemList = document.selectNodes("//root/item");
			Element element = null;
			for(int i = 0; i < itemList.size(); i++)
			{
				element = (Element)itemList.get(i);
				document = DocumentHelper.parseText(element.asXML());
				if(element.attribute("selected")==null)
				{
					
				}
				else
				{
					if("true".equals(element.attribute("selected").getData().toString()))
					{
						in+="'"+document.selectSingleNode("//item/id").getText()+"',";
					}
				}
			}
		} catch (DocumentException e)
		{
			e.printStackTrace();
		}
		in += ")";
		in = in.replace(",)", ")");
		BaseEntityDaoImpl baseDao = new BaseEntityDaoImpl();
		baseDao.deleteByHql("delete TabUserRole model where model.id in "+in);
		return "<data><result>ok</result><uuid></uuid><info>删除成功</info></data>";
	}
	public String update(String xmlStr)//更新报送信息
	{
		String dataXml="";
		try
		{
			Document document = DocumentHelper.parseText(xmlStr);
			dataXml = document.selectSingleNode("//data").asXML();
		} catch (DocumentException e)
		{
			e.printStackTrace();
		}
		BaseEntityDaoImpl baseDao = new BaseEntityDaoImpl();
		XStream xs = new XStream(new DomDriver());
		String defaultFormat = "yyyy-MM-dd HH:mm:ss";
		String[] acceptableFormat = {"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd","yyyy-MM"};
		xs.registerConverter(new DateConverter(defaultFormat,acceptableFormat));
		xs.registerConverter(new XStreamClobConverter());
		xs.alias("data", TabRole.class);
		TabRole entity = (TabRole)xs.fromXML(dataXml);
		baseDao.updateEntity(entity);
		return "<data><result>ok</result><uuid></uuid><info>更新成功</info></data>";
	}
	public String genDetail(String id)
	{
		BaseEntityDaoImpl baseDao = new BaseEntityDaoImpl();
		TabRole entity = new TabRole();
		entity = (TabRole)baseDao.findByPrimaryKey(entity, "id", id);
		XStream xs = new XStream(new DomDriver());
		xs.alias("data", TabRole.class);
		String xmlStr = xs.toXML(entity);
		return xmlStr;
	}
	public String genAll()
	{
		BaseEntityDaoImpl baseDao = new BaseEntityDaoImpl();
		List list = baseDao.findAll(TabRole.class.getName());
		String result = "<data>";
		XStream xs = new XStream(new DomDriver());
		String defaultFormat = "yyyy-MM-dd";
		String[] acceptableFormat = {"yyyy-MM"};
		xs.registerConverter(new DateConverter(defaultFormat,acceptableFormat));
		xs.registerConverter(new XStreamClobConverter());
		xs.alias("item", TabRole.class);
		for (int i =0; i<list.size(); i++)
		{
			TabRole entity = (TabRole)list.get(i);
			result+=xs.toXML(entity);
		}
		result+="</data>";
		return result.replace("00:00:00.0", "");
	}
	public String genWithCondition(String condition)
	{
		BaseEntityDaoImpl baseDao = new BaseEntityDaoImpl();
		String result = "<data>";
		try
		{
			Document document = DocumentHelper.parseText(condition);
			String corpName =  "";
			String code =  "";
			String title =  "";
			String corpId = "";
			String deptId = "";
			if(document.selectSingleNode("//condition/corpName")!=null)
			{
				corpName = document.selectSingleNode("//condition/corpName").getText();
				
			}
			if(document.selectSingleNode("//condition/code")!=null)
			{
				code = document.selectSingleNode("//condition/code").getText();
				
			}
			if(document.selectSingleNode("//condition/title")!=null)
			{
				title = document.selectSingleNode("//condition/title").getText();
				
			}
			if(document.selectSingleNode("//condition/corpId")!=null)
			{
				corpId = document.selectSingleNode("//condition/corpId").getText();
				
			}
			if(document.selectSingleNode("//condition/deptId")!=null)
			{
				deptId = document.selectSingleNode("//condition/deptId").getText();
				
			}
			String hql = "";
			hql+="from TabRole model where model.corpName like '%"+corpName+"%'";
			hql+=" and model.code like '%"+code+"%'";
			hql+=" and model.title like '%"+title+"%'";
			hql+=" and model.corpId like '%"+corpId+"%'";
			hql+=" and model.deptId like '%"+deptId+"%'";
			List list = baseDao.findByHql(hql);
			XStream xs = new XStream(new DomDriver());
			String defaultFormat = "yyyy-MM";
			String[] acceptableFormat = {"yyyy-MM"};
			xs.registerConverter(new DateConverter(defaultFormat,acceptableFormat));
			xs.registerConverter(new XStreamClobConverter());
			xs.alias("item", TabRole.class);
			for (int i =0; i<list.size(); i++)
			{
				TabRole entity = (TabRole)list.get(i);
				result+=xs.toXML(entity);
			}
		} catch (DocumentException e)
		{
			e.printStackTrace();
		}
		result+="</data>";
		return result.replace("-01 00:00:00.0", "");
	}
	public String genForClient(String condition)
	{
		BaseEntityDaoImpl baseDao = new BaseEntityDaoImpl();
		String result = "<data>";
		try
		{
			Document document = DocumentHelper.parseText(condition);
			String corpId = "";
			String deptId = "";
			if(document.selectSingleNode("//condition/corpId")!=null)
			{
				corpId = document.selectSingleNode("//condition/corpId").getText();
				
			}
			if(document.selectSingleNode("//condition/deptId")!=null)
			{
				deptId = document.selectSingleNode("//condition/deptId").getText();
				
			}
			String hql = "";
			hql+="from TabRole model where model.corpId='"+corpId+"'";
			hql+=" and model.deptId='"+deptId+"'";
			List list = baseDao.findByHql(hql);
			XStream xs = new XStream(new DomDriver());
			String defaultFormat = "yyyy-MM";
			String[] acceptableFormat = {"yyyy-MM"};
			xs.registerConverter(new DateConverter(defaultFormat,acceptableFormat));
			xs.registerConverter(new XStreamClobConverter());
			xs.alias("item", TabRole.class);
			for (int i =0; i<list.size(); i++)
			{
				TabRole entity = (TabRole)list.get(0);
				result+=xs.toXML(entity);
			}
		} catch (DocumentException e)
		{
			e.printStackTrace();
		}
		result+="</data>";
		return result.replace("-01 00:00:00.0", "");
	}
	public String genUserWithRole(String roleId)
	{
		BaseEntityDaoImpl baseDao = new BaseEntityDaoImpl();
		List userRoleList = baseDao.findByHql("from TabUserRole model where model.roleId='"+roleId+"'");
		String result = "<data>";
		for(int i = 0; i < userRoleList.size(); i++)
		{
			 
			TabUserRole entity = (TabUserRole)userRoleList.get(i);
			String userId = entity.getUserId();
			String id = entity.getId();
			String userType = entity.getUserType();
			if("engineer".equals(userType))
			{
				TabEngineer engineer = new TabEngineer();
				engineer = (TabEngineer)baseDao.findByPrimaryKey(engineer, "id", userId);
				if(engineer!=null)
				{
					result+="<item>";
						result+="<code>"+engineer.getJn()+"</code>";
						result+="<id>"+id+"</id>";
						result+="<realName>"+engineer.getRealname()+"</realName>";
						result+="<userName>"+engineer.getUsername()+"</userName>";
						result+="<lxfs>"+engineer.getPhone()+"/"+engineer.getMobile()+"/"+engineer.getEmail()+"</lxfs>";
						result+="<userId>"+engineer.getId()+"</userId>";
						result+="<roleId>"+roleId+"</roleId>";
						result+="<userType>engineer</userType>";
					result+="</item>";
				}
			}
			else if("client".equals(userType))
			{
				TabClient client = new TabClient();
				client = (TabClient)baseDao.findByPrimaryKey(client, "id", userId);
				if(client!=null)
				{
					result+="<item>";
					result+="<id>"+id+"</id>";
						result+="<code>"+client.getClientno()+"</code>";
						result+="<realName>"+client.getRealname()+"</realName>";
						result+="<userName>"+client.getUsername()+"</userName>";
						result+="<roleId>"+roleId+"</roleId>";
						result+="<lxfs>"+client.getPhone()+"/"+client.getMobile()+"/"+client.getEmail()+"</lxfs>";
						result+="<userId>"+client.getId()+"</userId>";
						result+="<userType>client</userType>";
					result+="</item>";
				}
			}
		}
		result+="</data>";
		return result;
	}
	public String genUsers(String roleId)
	{
		BaseEntityDaoImpl baseDao = new BaseEntityDaoImpl();
		List userRoleList = baseDao.findByHql("from TabUserRole model where model.roleId='"+roleId+"'");
		String result = "<data>";
		String ids="(";
		for(int i = 0; i < userRoleList.size(); i++)
		{
			
			TabUserRole entity = (TabUserRole)userRoleList.get(i);
			String userId = entity.getUserId();
			ids+="'"+userId+"',";
		}
		ids+=")";
		ids=ids.replace("',)", "')");
		List engineerList = new ArrayList();
		if(!"()".equals(ids))
		{
			engineerList = baseDao.findByHql("from TabEngineer model where model.id not in "+ids);
		}
		else
		{
			engineerList = baseDao.findByHql("from TabEngineer model");
		}
		for(int i = 0 ; i < engineerList.size(); i++)
		{
			TabEngineer engineer = (TabEngineer)engineerList.get(i);
			result+="<item>";
			result+="<code>"+engineer.getJn()+"</code>";
			result+="<realName>"+engineer.getRealname()+"</realName>";
			result+="<userName>"+engineer.getUsername()+"</userName>";
			result+="<lxfs>"+engineer.getPhone()+"/"+engineer.getMobile()+"/"+engineer.getEmail()+"</lxfs>";
			result+="<id>"+engineer.getId()+"</id>";
			result+="<userType>engineer</userType>";
			result+="<eoc>工程师</eoc>";
			result+="</item>";
		}
		List clientList = new ArrayList();
		if(!"()".equals(ids))
		{
			clientList = baseDao.findByHql("from TabClient model where model.id not in "+ids);
		}
		else
		{
			clientList = baseDao.findByHql("from TabClient model");
		}
		for(int i = 0; i < clientList.size(); i++)
		{
			
			TabClient client = (TabClient)clientList.get(i);
				result+="<item>";
				result+="<code>"+client.getClientno()+"</code>";
				result+="<realName>"+client.getRealname()+"</realName>";
				result+="<userName>"+client.getUsername()+"</userName>";
				result+="<lxfs>"+client.getPhone()+"/"+client.getMobile()+"/"+client.getEmail()+"</lxfs>";
				result+="<id>"+client.getId()+"</id>";
				result+="<userType>client</userType>";
				result+="<eoc>用户</eoc>";
				result+="</item>";
		}
		result+="</data>";
		return result;
	}
	public String addUserRole(String roleId,String users)
	{
		BaseEntityDaoImpl baseDao = new BaseEntityDaoImpl();
		try
		{
			Document document = DocumentHelper.parseText(users);
			List nodes = document.selectNodes("//data/item");
			for(int i = 0; i < nodes.size(); i++)
			{
				Element element = (Element)nodes.get(i);
				if(element.attribute("selected")!=null&&"true".equals(element.attribute("selected").getText()))
				{
					String userId = element.selectSingleNode("id").getText();
					String userType = element.selectSingleNode("userType").getText();
					TabUserRole userRole = new TabUserRole();
					userRole.setId(UUID.randomUUID().toString().substring(0,31));
					userRole.setRoleId(roleId);
					userRole.setUserId(userId);
					userRole.setUserType(userType);
					baseDao.insertEntity(userRole);
				}
			}
		} catch (DocumentException e)
		{
			e.printStackTrace();
		}
		return "";
	}
	public String deleteUserRole(String roleId,String userId)
	{
		BaseEntityDaoImpl baseDao = new BaseEntityDaoImpl();
		baseDao.execute("delete from TabUserRole model where model.roleId='"+roleId+"' and model.userId='"+userId+"'");
		return "";
	}
	public String deleteUserRoleById(String roleId,String userId)
	{
		BaseEntityDaoImpl baseDao = new BaseEntityDaoImpl();
		baseDao.execute("delete from TabUserRole model where model.roleId='"+roleId+"' and model.userId='"+userId+"'");
		return "";
	}
	
	public String addAccess(String accessXml)
	{
		BaseEntityDaoImpl baseDao = new BaseEntityDaoImpl();
		XStream xs = new XStream(new DomDriver());
		String defaultFormat = "yyyy-MM-dd";
		String[] acceptableFormat = {"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd","yyyy-MM"};
		xs.registerConverter(new DateConverter(defaultFormat,acceptableFormat));
		xs.registerConverter(new XStreamClobConverter());
		xs.alias("data", TabAccessMartrix.class);
		TabAccessMartrix entity = (TabAccessMartrix)xs.fromXML(accessXml);
		entity.setId(UUID.randomUUID().toString().substring(0,31));
		baseDao.insertEntity(entity);
		return "<data><result>ok</result><uuid>"+entity.getId()+"</uuid><info>添加成功</info></data>";
	}
	public String addRoleAccess(String roleId, String accessInfo)
	{
		BaseEntityDaoImpl baseDao = new BaseEntityDaoImpl();
		accessInfo = accessInfo.substring(0,accessInfo.length()-1);
		baseDao.execute("delete TabRoleAccess model where model.roleId='"+roleId+"'");
		String hql = "from TabAccessMartrix model where model.accessCode in ("+accessInfo+")";
		List accessList = baseDao.findByHql(hql);
		for(int i = 0; i < accessList.size(); i++)
		{
			TabAccessMartrix access = (TabAccessMartrix)accessList.get(i);
			String accessId = access.getId();
			String accessCode = access.getAccessCode();
			TabRoleAccess entity = new TabRoleAccess();
			entity.setId(UUID.randomUUID().toString().substring(0,31));
			entity.setAccessId(accessId);
			entity.setRoleId(roleId);
			entity.setAccessCode(accessCode);
			baseDao.insertEntity(entity);
		}
		return "<data><result>ok</result><uuid></uuid><info>添加成功</info></data>";
	}
}
